# To change this template, choose Tools | Templates
# and open the template in the editor.

from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
from game.client.render.Camera import *
from game.client.render.BlockRenderer import *
from game.client.render.TerrainRenderer import *

class MainRenderer:

    def __init__(self, client):
        self.client = client
        self.ablock = BlockRenderer((0.0, 0.0, 0.0),(255.0, 0.0, 0.0))
        self.grid_display_list = None
        self.terrain = TerrainRenderer(client)

    def init(self):
        glEnable(GL_DEPTH_TEST)

        glShadeModel(GL_FLAT)
        glClearColor(1.0, 1.0, 1.0, 0.0)

        glEnable(GL_COLOR_MATERIAL)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glLight(GL_LIGHT0, GL_POSITION,  (0, 10, 10, 0))

        glMaterial(GL_FRONT, GL_AMBIENT, (0.1, 0.1, 0.1, 1.0))
        glMaterial(GL_FRONT, GL_DIFFUSE, (1.0, 1.0, 1.0, 1.0))

        self.terrain.init()

    def resize(self, width, height):
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(60.0, float(width)/height, .1, 100000.)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

    def render(self):
        # Clear the screen, and z-buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        self.client.camera.set_camera()

        # Light must be transformed as well
        #glLight(GL_LIGHT0, GL_POSITION,  (0, 1.5, 1, 0))

        #self.terrain.render()
        #self.render_grid(1,10)
        #self.ablock.render()
        self.terrain.render()


    def render_grid(self, size, count):

        self.build_grid(size, count)

        glPushMatrix()

        #Draw xy in green
        glColor( (0.0, 200.0, 0.0))
        glCallList(self.grid_display_list)

        #Draw xz in blue
        glRotatef(90.0, 1.0, 0.0, 0.0)
        glColor( (0.0, 0.0, 200.0))
        glCallList(self.grid_display_list)

        #Draw yz in red
        glRotatef(90.0, 0.0, 1.0, 0.0)
        glColor( (200.0, 0.0, 0.0))
        glCallList(self.grid_display_list)

        glPopMatrix()

    def build_grid(self, size, count):
        if self.grid_display_list is None:

            # Create a display list
            self.grid_display_list = glGenLists(1)
            glNewList(self.grid_display_list, GL_COMPILE)

            glBegin(GL_LINES)
            for x in xrange(-count,count+1):
                glVertex( x*size, -count*size )
                glVertex( x*size, count*size )
            glEnd()

            glBegin(GL_LINES)
            for y in xrange(-count,count+1):
                glVertex( -count*size, y*size )
                glVertex( count*size, y*size )
            glEnd()

            # End the display list
            glEndList()
            
